package com.user.service.impl;

import com.user.model.entity.Message;
import com.user.model.entity.User;
import com.user.model.vo.MessageVo;
import com.user.model.vo.ParamVo;
import com.user.param.Result;
import com.user.repositories.MessageRepository;
import com.user.service.MessageService;
import com.user.util.CatchUtil;
import com.user.util.GetUserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageRepository messageRepository;

    @Override
    public Result putMessage(MessageVo messageVo) {
        Message message = new Message();
        BeanUtils.copyProperties(messageVo,message);

        messageRepository.save(message);
        return new Result(Result.SUCCESS_CODE);
    }

    @Override
    public Result getMessageList(String token) {
        User user = new User();
        user = GetUserUtil.loginUser();
        if (user == null) {
            CatchUtil catchUtil = new CatchUtil();
            user = (User) catchUtil.getCatch(token);
        }
        String userId = user.getId();
        List<Message> messages = messageRepository.findAllByUserIdAndDeletedOrderByReaded(userId,'N');
        int count = messageRepository.getCount(userId);
        ParamVo paramVo = new ParamVo();
        paramVo.setCount(count);
        paramVo.setObjects(messages);
        return new Result(paramVo);
    }
}
